<template>
  <view class="thesis-guidance-page">
    <!-- 顶部导航栏 -->

    <!-- 标签页导航 -->
    <view class="tabs-nav">
      <view class="tab-item" :class="{ active: currentTab === 0 }" @click="switchTab(0)">
        <text>论文求助</text>
      </view>
      <view class="tab-item" :class="{ active: currentTab === 1 }" @click="switchTab(1)">
        <text>专家推荐</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content-area">
      <!-- 论文求助标签页 -->
      <view v-if="currentTab === 0" class="thesis-assistance-tab">
        <view class="assistance-list">
          <view class="assistance-card" v-for="(item, index) in assistanceList" :key="item.id || index" @click="goAssistanceDetail(item)">
            <text class="status-tag">{{ getStatusText(item) }}</text>
            <view class="card-content">
              <view class="thumbnail">
                <image :src="item.avatar" :alt="item.title" />
              </view>
              <view class="content-info">
                <text class="title">{{ item.title }}</text>
                <text class="description">{{ item.description }}</text>
                <text class="date">{{ item.date }}</text>
              </view>
            </view>
            <button class="consult-btn" @click.stop="consultNow(item)">
              <text>立即咨询</text>
            </button>
          </view>

          <!-- 加载状态提示 -->
          <view class="loading-footer" v-if="loading && assistanceList.length > 0">
            <text class="loading-text">加载中...</text>
          </view>

          <!-- 没有更多数据提示 -->
          <view class="no-more-footer" v-if="!hasMore && assistanceList.length > 0 && !loading">
            <text class="no-more-text">没有更多数据了</text>
          </view>

          <!-- 空状态 -->
          <EmptyState v-if="!loading && assistanceList.length === 0" title="暂无论文求助信息" description="还没有人发布论文求助，快来发布第一个吧" />
        </view>
      </view>

      <!-- 专家推荐标签页 -->
      <view v-if="currentTab === 1" class="expert-recommendation-tab">
        <view class="expert-list">
          <view class="expert-card" v-for="(expert, index) in expertList" :key="expert.id || index" @click="goExpertDetail(expert)">
            <view class="expert-avatar">
              <image :src="expert.avatar || '/static/images/default-avatar.png'" :alt="expert.name" />
            </view>
            <view class="expert-info">
              <view class="expert-header">
                <text class="expert-name">{{ expert.name }}</text>
                <view class="rating">
                  <text class="rating-stars">{{ expert.rating || "0.0" }}</text>
                  <text class="rating-text">{{ expert.ratingText || "暂无评价" }}</text>
                </view>
              </view>
              <text class="expert-title">{{ expert.title || expert.academicTitle || "导师" }}</text>
              <text class="expert-specialty">{{ expert.specialty || expert.researchDirection || "暂无研究方向" }}</text>
              <view class="expert-stats">
                <text class="stat-item">指导{{ expert.guidanceCount || expert.totalStudents || 0 }}篇</text>
                <text class="stat-item">成功率{{ expert.successRate || expert.completionRate || 0 }}%</text>
              </view>
            </view>
            <button class="contact-btn" @click.stop="contactExpert(expert)">
              <text>联系专家</text>
            </button>
          </view>

          <!-- 加载状态提示 -->
          <view class="loading-footer" v-if="expertLoading && expertList.length > 0">
            <text class="loading-text">加载中...</text>
          </view>

          <!-- 没有更多数据提示 -->
          <view class="no-more-footer" v-if="!expertHasMore && expertList.length > 0 && !expertLoading">
            <text class="no-more-text">没有更多数据了</text>
          </view>

          <!-- 空状态 -->
          <EmptyState v-if="!expertLoading && expertList.length === 0" title="暂无专家推荐" description="暂时没有可推荐的专家，请稍后再试" />
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getThesisRequirementPageList, getThesisSupervisorPageList } from "@/api/thesis.js";
import EmptyState from "@/components/common/EmptyState.vue";

export default {
  components: {
    EmptyState,
  },
  data() {
    return {
      currentTab: 0,

      // 论文求助数据
      assistanceList: [],

      // 论文求助分页参数
      page: 1,
      limit: 20,
      loading: false,
      hasMore: true,

      // 专家推荐数据
      expertList: [],

      // 专家推荐分页参数
      expertPage: 1,
      expertLimit: 20,
      expertLoading: false,
      expertHasMore: true,
    };
  },
  methods: {
    // 加载论文求助列表
    async loadAssistanceList(isRefresh = false) {
      if (this.loading) return;

      if (isRefresh) {
        this.page = 1;
        this.hasMore = true;
        this.assistanceList = [];
      }

      if (!this.hasMore && !isRefresh) {
        return;
      }

      this.loading = true;

      try {
        const params = {
          page: this.page,
          limit: this.limit,
        };

        const res = await getThesisRequirementPageList(params);

        if (res.code === 200 && res.data) {
          const list = Array.isArray(res.data.list) ? res.data.list : [];

          // 转换数据格式以适配模板
          const formattedList = list.map((item) => ({
            id: item.id,
            title: item.thesisTitle || "未命名论文",
            description: this.formatDescription(item.researchContent || item.researchBackground || ""),
            date: this.formatDate(item.createTime || item.updateTime),
            thumbnail: this.getThumbnail(item),
            thesisType: item.thesisType,
            urgencyLevel: item.urgencyLevel,
            researchField: item.researchField,
            budget: item.budget,
            completionDays: item.completionDays,
            currentStage: item.currentStage,
          }));

          if (isRefresh) {
            this.assistanceList = formattedList;
          } else {
            this.assistanceList = this.assistanceList.concat(formattedList);
          }

          // 判断是否还有更多数据
          const total = res.data.total || 0;
          const currentTotal = this.assistanceList.length;

          // 如果返回的数据少于limit，说明没有更多了
          if (list.length < this.limit) {
            this.hasMore = false;
          } else {
            // 如果当前总数小于总记录数，说明还有更多
            this.hasMore = currentTotal < total;
          }

          // 如果有更多数据，页码加1
          if (this.hasMore) {
            this.page++;
          }
        } else {
          // 接口返回错误
          this.hasMore = false;
          if (!isRefresh) {
            uni.showToast({
              title: res.message || "加载失败",
              icon: "none",
            });
          }
        }
      } catch (error) {
        console.error("加载论文求助列表失败:", error);
        this.hasMore = false;
        if (!isRefresh) {
          uni.showToast({
            title: "加载失败，请重试",
            icon: "none",
          });
        }
      } finally {
        this.loading = false;
      }
    },

    // 加载专家推荐列表
    async loadExpertList(isRefresh = false) {
      if (this.expertLoading) return;

      if (isRefresh) {
        this.expertPage = 1;
        this.expertHasMore = true;
        this.expertList = [];
      }

      if (!this.expertHasMore && !isRefresh) {
        return;
      }

      this.expertLoading = true;

      try {
        const params = {
          page: this.expertPage,
          limit: this.expertLimit,
        };

        const res = await getThesisSupervisorPageList(params);

        if (res.code === 200 && res.data) {
          const list = Array.isArray(res.data.list) ? res.data.list : [];

          // 转换数据格式以适配模板
          const formattedList = list.map((item) => {
            // 计算评分文本
            const rating = item.ratingScore || 0;
            let ratingText = "暂无评价";
            if (rating >= 4.8) {
              ratingText = "好评如潮";
            } else if (rating >= 4.5) {
              ratingText = "专业可靠";
            } else if (rating >= 4.0) {
              ratingText = "经验丰富";
            } else if (rating > 0) {
              ratingText = "指导细致";
            }

            // 计算成功率
            const totalStudents = item.totalStudents || 0;
            const successfulGraduates = item.successfulGraduates || 0;
            const successRate = totalStudents > 0 ? Math.round((successfulGraduates / totalStudents) * 100) : item.completionRate ? Math.round(item.completionRate * 100) : 0;

            return {
              id: item.id,
              name: item.name || "未命名导师",
              title: item.academicTitle || item.administrativeTitle || "导师",
              specialty: item.researchDirection || item.expertiseFields || "暂无研究方向",
              avatar: item.avatar || "/static/images/default-avatar.png",
              rating: rating.toFixed(1),
              ratingText: ratingText,
              guidanceCount: item.totalStudents || 0,
              successRate: successRate,
              // 保留原始数据字段，方便后续使用
              academicTitle: item.academicTitle,
              researchDirection: item.researchDirection,
              totalStudents: item.totalStudents,
              successfulGraduates: item.successfulGraduates,
              completionRate: item.completionRate,
              ratingScore: item.ratingScore,
              personalProfile: item.personalProfile,
              department: item.department,
              workUnit: item.workUnit,
            };
          });

          if (isRefresh) {
            this.expertList = formattedList;
          } else {
            this.expertList = this.expertList.concat(formattedList);
          }

          // 判断是否还有更多数据
          const total = res.data.total || 0;
          const currentTotal = this.expertList.length;

          // 如果返回的数据少于limit，说明没有更多了
          if (list.length < this.expertLimit) {
            this.expertHasMore = false;
          } else {
            // 如果当前总数小于总记录数，说明还有更多
            this.expertHasMore = currentTotal < total;
          }

          // 如果有更多数据，页码加1
          if (this.expertHasMore) {
            this.expertPage++;
          }
        } else {
          // 接口返回错误
          this.expertHasMore = false;
          if (!isRefresh) {
            uni.showToast({
              title: res.message || "加载失败",
              icon: "none",
            });
          }
        }
      } catch (error) {
        console.error("加载专家推荐列表失败:", error);
        this.expertHasMore = false;
        if (!isRefresh) {
          uni.showToast({
            title: "加载失败，请重试",
            icon: "none",
          });
        }
      } finally {
        this.expertLoading = false;
      }
    },

    // 格式化描述文本
    formatDescription(text) {
      if (!text) return "暂无描述";
      const maxLength = 60;
      return text.length > maxLength ? text.substring(0, maxLength) + "..." : text;
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return "";
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}.${month}.${day}`;
    },

    // 获取缩略图（如果有附件）
    getThumbnail(item) {
      // 如果有附件ID，可以尝试获取第一个附件的缩略图
      // 这里暂时使用默认图片
      return item.thumbnail || "http://img.1637.com/2015/07/10/YZS1VNIJE3HR504910.jpg";
    },

    switchTab(index) {
      this.currentTab = index;
      console.log("切换标签页:", index);
      // 切换到论文求助标签时，如果列表为空则加载
      if (index === 0 && this.assistanceList.length === 0) {
        this.loadAssistanceList(true);
      }
      // 切换到专家推荐标签时，如果列表为空则加载
      if (index === 1 && this.expertList.length === 0) {
        this.loadExpertList(true);
      }
    },
    goAssistanceDetail(item) {
      console.log("查看求助详情:", item);
      uni.navigateTo({
        url: `/pages/fast/thesis-detail?id=${item.id}`,
      });
    },
    consultNow(item) {
      console.log("立即咨询:", item);
      uni.showModal({
        title: "确认咨询",
        content: `确定要咨询《${item.title}》吗？`,
        success: (res) => {
          if (res.confirm) {
            uni.showToast({
              title: "咨询请求已提交",
              icon: "success",
            });
          }
        },
      });
    },
    goExpertDetail(expert) {
      console.log("查看专家详情:", expert);
      uni.showModal({
        title: "专家详情",
        content: `${expert.name} - ${expert.title}\n专业领域：${expert.specialty}\n指导论文：${expert.guidanceCount}篇\n成功率：${expert.successRate}%`,
        success: (res) => {
          if (res.confirm) {
            this.contactExpert(expert);
          }
        },
      });
    },
    contactExpert(expert) {
      console.log("联系专家:", expert);
      uni.showModal({
        title: "联系专家",
        content: `确定要联系${expert.name}教授吗？`,
        success: (res) => {
          if (res.confirm) {
            uni.showToast({
              title: "联系请求已发送",
              icon: "success",
            });
          }
        },
      });
    },

    // 获取状态文本
    getStatusText(item) {
      if (item.currentStage) {
        const stageMap = {
          1: "需求确认",
          2: "文献综述",
          3: "开题报告",
          4: "实验设计",
          5: "数据分析",
          6: "初稿撰写",
          7: "修改完善",
          8: "最终定稿",
        };
        return stageMap[item.currentStage] || "进行中";
      }
      return "求助中";
    },
  },
  created() {
    this.loadAssistanceList();
  },
  onPullDownRefresh() {
    if (this.currentTab === 0) {
      this.loadAssistanceList(true).finally(() => {
        uni.stopPullDownRefresh();
      });
    } else if (this.currentTab === 1) {
      this.loadExpertList(true).finally(() => {
        uni.stopPullDownRefresh();
      });
    } else {
      uni.stopPullDownRefresh();
    }
  },
  onReachBottom() {
    // 论文求助标签页：加载更多
    if (this.currentTab === 0 && this.hasMore && !this.loading) {
      this.loadAssistanceList();
    }
    // 专家推荐标签页：加载更多
    if (this.currentTab === 1 && this.expertHasMore && !this.expertLoading) {
      this.loadExpertList();
    }
  },
};
</script>

<style lang="scss" scoped>
.thesis-guidance-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.tabs-nav {
  background: white;
  display: flex;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);

  .tab-item {
    flex: 1;
    padding: 30rpx 20rpx;
    text-align: center;
    font-size: 28rpx;
    color: #666;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;

    &.active {
      color: #ed6567;
      font-weight: 600;

      &::after {
        content: "";
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 60rpx;
        height: 4rpx;
        background: #ed6567;
        border-radius: 2rpx;
      }
    }

    text {
      display: block;
    }
  }
}

.content-area {
  padding: 0 20rpx;

  .thesis-assistance-tab,
  .expert-recommendation-tab {
    .assistance-list,
    .expert-list {
      .assistance-card,
      .expert-card {
        background: white;
        border-radius: 24rpx;
        margin-bottom: 20rpx;
        overflow: hidden;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-4rpx);
          box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.12);
        }
      }
    }
  }
}

.assistance-card {
  padding: 30rpx;
  position: relative;

  .status-tag {
    position: absolute;
    top: 20rpx;
    right: 20rpx;
    background: #ed6567;
    color: white;
    padding: 6rpx 16rpx;
    border-radius: 20rpx;
    font-size: 20rpx;
    font-weight: 500;
  }

  .card-content {
    display: flex;
    gap: 24rpx;
    margin-bottom: 20rpx;

    .thumbnail {
      width: 120rpx;
      height: 120rpx;
      border-radius: 16rpx;
      overflow: hidden;

      image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .content-info {
      flex: 1;

      .title {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 12rpx;
        display: block;
        line-height: 1.3;
      }

      .description {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 12rpx;
        display: block;
        line-height: 1.4;
      }

      .date {
        font-size: 22rpx;
        color: #999;
        display: block;
      }
    }
  }

  .consult-btn {
    width: 100%;
    background: #ed6567;
    color: white;
    border: none;
    border-radius: 50rpx;
    padding: 20rpx;
    font-size: 28rpx;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      background: #d55a54;
    }

    text {
      color: white;
    }
  }

  // 加载状态
  .loading-footer {
    padding: 40rpx 0;
    text-align: center;

    .loading-text {
      font-size: 26rpx;
      color: #999;
    }
  }
}
// 没有更多数据
.no-more-footer {
  padding: 40rpx 0;
  text-align: center;
  display: flex !important;
  justify-content: center;
  align-items: center;
  .no-more-text {
    font-size: 26rpx;
    color: #999;
    position: relative;
    text-align: center;

    &::before,
    &::after {
      content: "";
      position: absolute;
      top: 50%;
      width: 60rpx;
      height: 1rpx;
      background: #ddd;
    }

    &::before {
      left: -80rpx;
    }

    &::after {
      right: -80rpx;
    }
  }
}

.expert-card {
  padding: 30rpx;
  display: flex;
  align-items: center;
  gap: 24rpx;

  .expert-avatar {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    overflow: hidden;

    image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .expert-info {
    flex: 1;

    .expert-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 8rpx;

      .expert-name {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }

      .rating {
        display: flex;
        align-items: center;
        gap: 8rpx;

        .rating-stars {
          font-size: 24rpx;
          color: #ffc107;
          font-weight: 600;
        }

        .rating-text {
          font-size: 20rpx;
          color: #666;
        }
      }
    }

    .expert-title {
      font-size: 26rpx;
      color: #666;
      margin-bottom: 8rpx;
      display: block;
    }

    .expert-specialty {
      font-size: 24rpx;
      color: #999;
      margin-bottom: 12rpx;
      display: block;
    }

    .expert-stats {
      display: flex;
      gap: 16rpx;

      .stat-item {
        font-size: 22rpx;
        color: #666;
        background: #f8f9fa;
        padding: 4rpx 12rpx;
        border-radius: 12rpx;
      }
    }
  }

  .contact-btn {
    background: #ed6567;
    color: white;
    border: none;
    border-radius: 40rpx;
    padding: 16rpx 24rpx;
    font-size: 26rpx;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      background: #d55a54;
    }

    text {
      color: white;
    }
  }
}
</style>
